import Mime from 'mime';
import { analyzeFilePurpose } from '../lib/analyzeFilePurpose.js';
import { getContext } from '../lib/context.js';
import { runTasksInParallel, getFileExtension } from '../lib/handy.js';
import { showModal } from '../lib/modal.js';
import { initUser } from '../lib/user.js';
import { convertPdfToImage } from '../lib/pdf.js';

export default {
    data() {
        return {
            fileName: '',
        };
    },
    methods: {
        showBaseInfoModal() {
            showModal('base-info-modal');
        },
        async fileChange() {
            const context = getContext();
            const file = document.getElementById('fileInput').files[0];
            if (!file) {
                this.$emit('update:isFileExist', false);
                return;
            }
            this.fileName = file.name;
            context.isUploading = true;
            this.$emit('update:uploadStatus', '正在上传，请稍等...');
            const uuid = await initUser();
            this.$emit('update:isFileExist', true);
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/upload-zip');
            const formData = new FormData();
            formData.append('file', file);
            formData.append('uuid', uuid);
            xhr.onreadystatechange = async () => {
                context.isUploading = false;
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        const res = JSON.parse(xhr.responseText);
                        context.uploadStatus = `
                                <div class="file-name">${this.fileName}</div>
                                <div class="status">正在复合处理...</div>
                            `;
                        const zipFileHash = res.hash;
                        context.zipFileHash = zipFileHash;
                        context.fileList = res.fileList;
                        const tasks = [];
                        for (const pdfFile of res.fileList) {
                          
                          // 控制不同的流程状态，上传不同文件
                          console.log('---', pdfFile)

                        }
                        context.isUploading = true;
                        await runTasksInParallel(tasks, 3);
                        context.isUploading = false;
                        context.uploadStatus = `
                                <div class="file-name">${this.fileName}</div>
                                <div class="status">文件上传成功</div>
                            `;
                    } else {
                        this.$emit('update:uploadStatus', '上传失败');
                    }
                }
            };
            xhr.send(formData);
        },
        fileInputClickHandler(event) {
            const context = getContext();
            if (context.isUploading) {
                return;
            }
            console.log('click', event);
            document.getElementById('fileInput').click();
        },
        
        async parsePdf(pdfFile, zipFileHash) {
            if (Array.isArray(pdfFile.imageList)) {
                return;
            }
            const pdfFileName = pdfFile.fileName;
            const pdfFileHash = pdfFile.hash;

            console.log('从服务器取回pdf: ' + pdfFileName);

            const images = await this.downloadImages({
                fileHash: pdfFileHash,
                fileName: pdfFileName,
                zipFileHash,
            });

            if (!Array.isArray(images) || images.length == 0) {
                throw new Error('识别图片错误');
            }

            // 如果pdf里的所有图片已经转换成成功了，则直接返回
            const ifAllSettle = !images.filter((e) => !e.fileId).length;
            if (ifAllSettle) {
                pdfFile.imageList = images;
                return images;
            }
            pdfFile.images = images;
            // upload images
            const imageList = await this.uploadImages({
                pdfFileName,
                pdfFileHash,
                pdfImages: images,
                zipFileHash,
            });
            if (!Array.isArray(imageList) || !imageList.length) {
                console.error('pdf: ', pdfFile);
                throw new Error('转换PDF文件失败，未能转成图片');
            }
            pdfFile.imageList = imageList;
        },

        async uploadImages({
            pdfFileName,
            pdfFileHash,
            pdfImages,
            zipFileHash,
        }) {
            const context = getContext();
            const uuid = await initUser();
            const url = '/upload-images';
            const formData = new FormData();
            formData.append('uuid', uuid);
            formData.append('zipFileHash', zipFileHash);
            formData.append('fileName', pdfFileName);
            formData.append('fileHash', pdfFileHash);
            for (let image of pdfImages) {
                formData.append('images', image);
            }
            context.uploadStatus = '上传pdf图片到服务器：' + pdfFileName;
            const response = await fetch(url, {
                method: 'POST',
                body: formData,
            });
            console.log('response: ', response);
            const json = await response.json();
            console.log('json: ', json);
            if (json.code == 200) {
                console.log('upload images success');
                return json.imageList;
            } else {
                console.error('upload images error');
            }
        },
        async downloadImages({ zipFileHash, fileName, fileHash }) {
            const uuid = await initUser();
            const url = '/get-file';
            const formData = new FormData();
            formData.append('uuid', uuid);
            formData.append('zipFileHash', zipFileHash);
            formData.append('fileName', fileName);
            formData.append('fileHash', fileHash);
            const response = await fetch(url, {
                method: 'POST',
                body: formData,
            });
            const contentType = response.headers.get('Content-Type');
            if (contentType.includes('application/json')) {
                const json = await response.json();
                if (Array.isArray(json.imageList)) {
                    return json.imageList;
                }
                console.error('json: ', json);
                return;
            } else {
                const fileBlob = await response.blob();
                const ext = getFileExtension(fileName);
                const mime = Mime.getType(ext);
                const file = new File([fileBlob], fileName, { type: mime });
                if (['png', 'jpg', 'jpeg'].includes(ext)) {
                    return [file];
                }
                const images = await convertPdfToImage.call(this, file);
                console.log('images: ', images);
                return images;
            }
        },
    },
    props: {
        uploadStatus: String,
    },
    /* html */
    template: `
    <div class="upload-wrapper">
        <div class="title">上传材料</div>
        <div class="board">
            <div class="file-upload-instruct" v-on:click="fileInputClickHandler">
                <div v-if="uploadStatus" id="upload-status" v-html="uploadStatus"></div>
                <div class="instruct" v-else>
                    <div class="file-icon"><img src="/assets/upload-icon.png" /></div>
                    <div class="title">点击或将文件拖拽到这里上传</div>
                    <div class="support-ext">支持扩展名：.zip</div>
                </div>
            </div>
            <input type="file" id="fileInput" class="hide" name="file" accept="application/zip"
                @change="fileChange" />
            <div class="file-intro">
                <ul>
                    <li>zip包内需包含所有待审查的文档</li>
                    <li>文档格式可以是png或pdf</li>
                    <li>zip包内可以含有文件夹</li>
                    <li>文件名没有要求，但最好能体现文件内容</li>
                </ul>
                <div class="fill-basic-info" v-on:click="showBaseInfoModal">录入基本信息</div>
            </div>
        </div>
    </div>
    `,
};
